package com.huizhonglm.diap.core.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;

import com.huizhonglm.diap.DiapApplication;

import java.io.File;
import java.util.List;

/**
 * APk包操作类
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-01 15:42
 */
public class AppUtil {

    /**
     * 安装应用
     *
     * @param apkPath apk文件路径
     */
    public static void install(String apkPath) {
        Context context = DiapApplication.getInstance().getContext();
        File fileAPK = new File(apkPath);
        if (fileAPK.exists() && fileAPK.getName().toLowerCase().endsWith(".apk")) {
            Intent install = new Intent();
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.setAction(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(fileAPK), "application/vnd.android.package-archive");
            context.startActivity(install);// 安装
        }
    }

    /**
     * 卸载应用
     *
     * @param packageName 应用包名
     */
    public static void unInstall(String packageName) {
        Context context = DiapApplication.getInstance().getContext();
        if (isPackageExists(context, packageName)) {
            Uri packageURI = Uri.parse("package:" + packageName);
            Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
            context.startActivity(uninstallIntent);
        }
    }

    /**
     * 判断应用是否已安装
     *
     * @param packageName
     * @return
     */
    public static boolean isInstalled(String packageName) {
        Context context = DiapApplication.getInstance().getContext();
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        if (packages != null && packages.size() > 0) {
            for (PackageInfo info : packages) {
                if (info.packageName.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 打开应用
     *
     * @param packageName 包名
     */
    public static void open(Context context, String packageName) {

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo pkgInfo = null;
        try {
            pkgInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (pkgInfo == null) {
            return;
        }
        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(pkgInfo.packageName);
        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = context.getPackageManager().queryIntentActivities(resolveIntent, 0);
        ResolveInfo resolveInfo = resolveinfoList.iterator().next();
        if (resolveInfo != null) {
            // packagename = 参数packname
            String pkgName = resolveInfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String clsName = resolveInfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(pkgName, clsName);
            intent.setComponent(cn);
            context.startActivity(intent);
        }
    }

    /**
     * 检测该包名所对应的应用是否存在（eg.com.org）
     *
     * @param context current appliaction Content
     * @param packageName other appliaction package name
     * @return boolean
     */
    public static boolean isPackageExists(Context context, String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        try {
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }
}
